package com.ccloud.common.core.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;

import java.util.*;

/**
 * @author frb
 */
public class SignUtil {

    public static final long SIGN_EXPIRE = 60 * 15 * 1000;

    public static final String APP_SECRET = "155asga-241fa";

    /**
     * 通过传入参数加密
     * @param appKey appKey，每个系统唯一
     * @param timestamp 时间戳
     * @param appSecret 密钥，需要申请
     * @return 加密串
     */
    public static String sign(String appKey, String timestamp, String appSecret) {
        Map<String, String> signMap = new HashMap<>();
        signMap.put("appKey",appKey);
        signMap.put("timestamp",timestamp);
        String signData = getSignData(signMap);
        byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_MD5, appSecret).hmac(signData);
        return new String(Base64.encodeBase64(hmac));
    }

    public static String sign(Map<String, String> params) {
        String signData = getSignData(params);
        byte[] hmac = new HmacUtils(HmacAlgorithms.HMAC_MD5, APP_SECRET).hmac(signData);
        return new String(Base64.encodeBase64(hmac));
    }

    public static boolean isExpire(long timestamp) {
        long now = System.currentTimeMillis();
        if (now - timestamp > SIGN_EXPIRE) {
            return true;
        }
        return false;
    }

    public static String getSignData(Map<String, String> params) {
        StringBuilder content = new StringBuilder();
        //  自然排序
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            if ("sign".equals(key)) {
                continue;
            }
            String value = params.get(key);
            if (value != null) {
                content.append(i == 0 ? "" : "&").append(key).append("=").append(value);
            } else {
                content.append(i == 0 ? "" : "&").append(key).append("=");
            }
        }
        return content.toString();
    }

    public static void main(String[] args) {
        String times = String.valueOf(System.currentTimeMillis());
        System.out.println(times);
        System.out.println(sign("TYSF",times,"155asga-241fa"));
    }

}
